<template>
  <!--经办人管理-->
  <section class="page agent-manage">
    <el-button @click="changeAgent()" v-if="queueType !== 'OUTER'"
      >选择经办</el-button
    >
    <el-button @click="changeAgent()" v-else>选择外包公司</el-button>
    <div class="row">
      <data-box-page-pick
        :data="selectAgent.slice((this.page - 1) * this.size, (this.page - 1) * this.size + this.size)"
        ref="multipleTable"
        class="pickTable"
      >
        <template slot="columns">
          <el-table-column
            label="序号"
            type="index"
            width="60"
          ></el-table-column>
          <!-- 非外包 -->
          <el-table-column
            prop="handCode" label="经办代号"
            :min-width="$helper.getColumnWidth(4)"
            show-overflow-tooltip
            v-if="queueType !== 'OUTER'"
          ></el-table-column>
          <el-table-column
            prop="realName"  label="姓名"
            :min-width="$helper.getColumnWidth(4)"
            show-overflow-tooltip
            v-if="queueType !== 'OUTER'"
          ></el-table-column>
          <el-table-column
            prop="deptName"
            label="所属机构"
            :min-width="$helper.getColumnWidth(4)"
            show-overflow-tooltip
            v-if="queueType !== 'OUTER'"
          ></el-table-column>

          <!-- 外包 -->
          <el-table-column
            prop="divisionCode"
            label="外包编号"
            :min-width="$helper.getColumnWidth(5)"
            show-overflow-tooltip
            v-if="queueType === 'OUTER'"
          >
          </el-table-column>
          <el-table-column
            prop="outOrgName"
            label="外包公司"
            :min-width="$helper.getColumnWidth(6)"
            show-overflow-tooltip
            v-if="queueType === 'OUTER'"
          >
          </el-table-column>
          <el-table-column
            prop="caseSwitch"
            label="分案开关"
            :min-width="$helper.getColumnWidth(4)"
            show-overflow-tooltip
            v-if="queueType !== 'OUTER'"
          >
            <template slot-scope="scope">
                {{scope.row.caseSwitch === 'OPEN' ? "开启" : '关闭'}}
            </template>
          </el-table-column>
          <el-table-column
            prop="caseSwitch"
            label="分案开关"
            :min-width="$helper.getColumnWidth(4)"
            show-overflow-tooltip
            v-if="queueType === 'OUTER'"
          >
            <template slot-scope="scope">
              <!-- <div>
                  {{scope.row.caseSwitch === 'OPEN' ? "开启" : '关闭'}}
              </div> -->
                {{scope.row.caseSwitch === 'OPEN' ? "开启" : '关闭'}}
            </template>
          </el-table-column>
          <el-table-column
            prop="isAdmin"
            label="是否管理员"
            :min-width="$helper.getColumnWidth(4)"
            :formatter="row => $filter.dictConvert(row.isAdmin, 'isAdmin')"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              {{ scope.row.isAdmin === 1 ? "是" : "否" }}
            </template>
          </el-table-column>
          <el-table-column
            prop="userStatus"
            label="状态"
            :min-width="$helper.getColumnWidth(4)"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              {{ scope.row.userStatus === "DISABLED" ? "停用" : "启用" }}
            </template>
          </el-table-column>
          <el-table-column
            v-if="showGuzhi"
            prop="fixedCount"
            label="固值"
            :min-width="$helper.getColumnWidth(5)"
          >
            <template slot-scope="scope">
              <el-input v-model.trim="selectAgent[scope.$index].fixedCount" :maxlength="20" />
            </template>
          </el-table-column>
          <el-table-column
            v-if="showGuzhi"
            prop="proportion"
            label="比例(%)"
            :min-width="$helper.getColumnWidth(3)"
          >
            <template slot-scope="scope">
              <el-input v-model.trim="selectAgent[scope.$index].proportion" type="tel" @input="checkVal(selectAgent[scope.$index].proportion, scope.$index)" />
            </template>
          </el-table-column>
          <!-- <el-table-column
            prop="caseSwitch"
            label="操作"
            :min-width="$helper.getColumnWidth(4)"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <el-button
                type="text"
                @click="deleAgentBtn(scope.$index, selectAgent)"
                >删除</el-button
              >
            </template>
          </el-table-column> -->
        </template>
      </data-box-page-pick>
    </div>
    <div class="txtBox">
      <div v-if="!isOuter && queueType !== 'OUTER'"> 
        <span
          >已选中{{ selectAgent.length }}个经办，共{{ deptNameNum }}个机构参与，
          <span v-if="deptNameNum !== 1">分别</span>是<span
            v-for="item in dataFinds"
            :key="item.id"
            >{{ item.deptName }},
          </span></span
        >
      </div>
      <div v-else>
        <span>已选中{{ selectAgent.length }}个外包公司,<span v-if="deptNameNum !== 1">分别</span>是<span
            v-for="item in dataFinds"
            :key="item.id"
            >{{ item.realName }},
          </span></span>
      </div>
    </div>
    <div class="paginBox">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        class="paginn"
        :current-page="page"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="this.selectAgent.length"
      >
      </el-pagination>
    </div>
    <div class="texatBox" v-if="!isTeamUse">
      <el-form :model="numberValidateForm" ref="numberValidateForm">
        <el-form-item
          label="注记:"
          prop="remark"
          :rules="[
            { required: true, message: '注记不能为空', trigger: 'blur' }
          ]"
        >
          <el-input
            type="textarea"
            v-model.trim="numberValidateForm.remark"
            :maxlength="500"
          ></el-input>
        </el-form-item>
      </el-form>
    </div>
    <div class="texatBox" v-if="!isTeamUse">
      <span class="txtrem">历史注记:</span>
      <data-box-page-pick
        :data="historyTabData"
        ref="data-box"
        class="pickTable"
        :page="pageService"
        @onPageChange="queryHistory(queueId)"
      >
        <template slot="columns">
          <el-table-column
            label="序号"
            type="index"
            width="60"
          ></el-table-column>
          <el-table-column
            prop="createdDate"
            label="注记时间"
            :formatter="row => $filter.dateTimeFormat(row.createdDate)"
            :min-width="$helper.getColumnWidth(2)"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column
            prop="operatorCode"
            label="添加人"
            :min-width="$helper.getColumnWidth(2)"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column
            prop="remark"
            label="内容"
            :min-width="$helper.getColumnWidth(3)"
            show-overflow-tooltip
          >
          </el-table-column>
        </template>
      </data-box-page-pick>
    </div>
    <div class="operate-buttons" v-if="!isTeamUse">
      <el-button @click="close">取消</el-button>
      <el-button @click="commit">确定</el-button>
    </div>
    
    <el-form label-width="160px" class="isTeamUse queueRemark" v-if="isTeamUse">
      <el-row>
        <el-col :span="24">
          <el-form-item label="队列注记" class="team-note">
            <el-input
              v-model="teamUseQuery.queueRemark"
              type="textarea"
              disabled
              :maxlength="300"
              show-word-limit
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row class="lockEndDate">
        <el-col :span="8">
          <el-form-item
            label="锁定到期日期"
            prop="lockEndDate"
            class="input-style"
          >
            <el-select v-model="teamUseQuery.lockEndDate" disabled>
              <el-option
                v-for="{ code, name, index } in $dict.getDictData(
                  'LockEndDate'
                )"
                :key="index"
                :label="name"
                :value="code"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col
          :span="8"
          v-if="['MONTH_DAY', 'MONTH'].includes(teamUseQuery.lockEndDate)"
        >
          <el-form-item
            :label="
              teamUseQuery.lockEndDate === 'MONTH'
                ? '锁定至第X个自然月'
                : '锁定至第X月'
            "
            prop="expireMonth"
            class="input-style"
            id="expireDay"
          >
            <el-input
              v-model.trim="teamUseQuery.expireMonth"
              :maxlength="6"
              disabled
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col
          :span="8"
          v-if="['MONTH_DAY', 'DAY'].includes(teamUseQuery.lockEndDate)"
        >
          <el-form-item
            :label="
              teamUseQuery.lockEndDate === 'DAY'
                ? '锁定至第X个自然日'
                : '锁定至第X号'
            "
            prop="expireDay"
            class="input-style"
            id="expireDay"
          >
            <el-input v-model.trim="teamUseQuery.expireDay" disabled :maxlength="6"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="9" v-if="teamUseQuery.lockEndDate === 'SOME'">
          <el-form-item
            label="锁定到某个日期"
            prop="expireDate"
            class="input-style"
            id="expireDay"
          >
            <el-date-picker
              placeholder="请选择日期"
              type="date"
              v-model="teamUseQuery.expireDate"
              value-format="timestamp"
              disabled
            ></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="operate-buttons" v-if="isTeamUse">
      <el-button @click="close">取消</el-button>
      <el-button @click="next">下一步</el-button>
    </div>

    <!--队列案件设置经办弹出框-->
    <el-dialog
      title="经办设置"
      :center="true"
      :visible.sync="dialog.addAgent"
      width="800px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      append-to-body
    >
      <add-agent
        :realArr="realArr"
        :selected="selectAgent"
        :isTeamUse="isTeamUse"
        @close="dialog.addAgent = false"
        @listenToChildEvent="showMsgfromChild"
        :showGuzhi="showGuzhi"
        :treeClose="queueType === 'OUTER'"
        :queueId="queueId"
        :queueType="queueType"
        :dialogVisible="dialog.addAgent"
        ref="add-agent"
        @deallBtn="deallBtn"
        :departmentData="departmentData"
        :expandDefault="expandDefault"
        @getAgentData="getAgentData"
        @afterAgentChangeMethods="afterAgentChangeMethods"
      ></add-agent>
    </el-dialog>
  </section>
</template>

<script lang="ts">
import Vue from "vue";
import Component from "vue-class-component";
import { Layout, Dependencies } from "~/core/decorator";
import { PageService } from "~/utils/page.service";
import { Emit, Prop, Watch } from "vue-property-decorator";
import { Action, State, Mutation, Getter, namespace } from "vuex-class";
import DataForm from "~/components/common/data-form.vue";
import DataBoxPagePick from "~/components/common/data-box-page-pick-queueList.vue";
import DepartmentTree from "~/components/system-manage/department-tree.vue";
import DataTree from "~/components/common/data-tree.vue";
import AddAgent from "~/components/queue-manage/add-agent.vue";
import { QueueService } from "~/services/domain-service/queue-manage.service";
import { CaseQueueService } from "~/services/domain-service/case-queue.service";
import { DepartmentService } from "~/services/management-service/department.service";
import { CommonService } from "~/utils/common.service";
import { set } from "vue/types/umd";

@Layout("workspace")
@Component({
  components: {
    DepartmentTree,
    DataTree,
    AddAgent,
    DataBoxPagePick
  }
})
export default class AddAgentDetail extends Vue {

  @Prop({ default: false }) private isOuter
  @Prop() private selectArr
  @Prop({ default: false }) private isTeamUse;
  @Prop() private treeClose;
  @Prop() private queueId;
  @Prop() private queueType;
  @Prop() private showGuzhi;
  @Prop() private teamUseQuery;
  @Dependencies(PageService) private pageService: PageService;
  @Dependencies(QueueService) private queueService: QueueService;
  @Dependencies(DepartmentService) private departmentService: DepartmentService;
  @Dependencies(CaseQueueService) private caseQueueService: CaseQueueService;
  // @Prop() private departmentData;
  // @Prop() private expandDefault;
  @Prop() private realArr;
  private historyTabData = [];
  private dialog: any = {
    addAgent: false
  };
  private selectAgent: any[] = []
  private deptId: string = "";
  private dept: any = "";
  private deptCode: any = "";
  private departmentData: any = [];
  private expandDefault: any = "";
  private numberValidateForm: any = {
    remark: ""
  };
  private deptNameNum: any = "";
  private dataFinds: any = [];
  private value: any = "";
  private q: any = "";
  private page: any = 1;
  private size: any = 10;
  private afterAgentChangeVal: boolean = false

  @Emit("refreshList") public refreshList() {}
  @Emit("close") public close() {
    this.reset();
  }

  @Watch('selectArr') private selectArrChange() {
    this.page = 1
    this.selectArr.forEach(e => {
      e.id = e.agentId;
      e.outOrgName = e.realName;
      e.divisionCode = e.handCode;
    });
    this.selectAgent = this.selectArr
    this.dataHandler(this.selectAgent);
  }

  @Watch('selectAgent') private selectAgentChange() {
    this.dataHandler(this.selectAgent);
  }

  private next() {
    this.$emit("next", this.selectAgent, this.teamUseQuery) // 下一步按钮
  }

  private checkVal(value, index) { // 校验只能输入3位正整数
    if(this.$validator.regex.naturalNumber.test(value)) {
      if(JSON.stringify(value).length > 3) {
        this.$nextTick(() => {
          this.selectAgent[index].proportion = Number(value) > 100 ? '' : Number(value)
        })
      }
    } else {
      this.selectAgent[index].proportion = ''
    }
  }

  private mounted() {
    if (!this.isTeamUse) {
      this.queryHistory(this.queueId);
    }
  }

  private showMsgfromChild(listenToChildEvent) {
    this.selectAgent = listenToChildEvent
    this.selectAgent = listenToChildEvent.map(item => {
      return { ...item, divisionStatus: item.userStatus, id: item.agentId };
    });
    this.dataHandler(this.selectAgent);
  }
  private closed(val) { // 关闭后同步表格选中数据
    this.selectAgent = val
    this.dialog.addAgent = false
  }

  private afterAgentChangeMethods(val) {
    this.afterAgentChangeVal = val
  }

  /**
   * 历史注记
   */
  private queryHistory(ids) {
    this.caseQueueService
      .getHandleRemarksByQueueId({ id: ids }, this.pageService)
      .subscribe(data => {
        this.historyTabData = data;
      });
  }

  //重置经办人
  private reset() {
    if (!this.isTeamUse) {
      const dataBox: any = this.$refs["data-box"];
      dataBox.reset();
    }
    this.pageService.pageIndex = 1;
    this.deptId = "";
    this.dept = "";
    this.dataFinds = [];
  }

  private getAgentData() {
    this.queueService.viewHandlerMessage({ queueId: this.queueId }).subscribe(data => {
      if(this.queueType === "OUTER"){
        this.selectAgent = data.map(item => {
          item.id = item.agentId;
          item.outOrgName = item.realName;
          item.divisionCode = item.handCode;
          // item.divisionStatus = item.caseSwitch;
        });
      }
      this.selectAgent = data.map(item => {
        return { ...item, divisionStatus: item.userStatus, id: item.agentId };
      });
    });
    this.dataHandler(this.selectAgent);
  }

  // 获取全部机构
  private getAllDepartmentData() {
    // // 获取机构(权限控制)
    // this.departmentService.querySubDepartment().subscribe(data => {
    //   this.departmentData = this.$common.generateTreeData(data, {
    //     keyName: "id",
    //     parentKeyName: "parentId"
    //   });
    //   this.expandDefault = this.departmentData[0].deptCode;
    // })
    // 获取全部机构(权限控制)
    // this.departmentService.queryAllDepartment().subscribe(data => {
    //   this.departmentData = this.$common.generateTreeData(data, {
    //     keyName: "id",
    //     parentKeyName: "parentId"
    //   });
    //   this.expandDefault = this.departmentData[0].deptCode;
    // });
    // 获取全部机构(不做权限控制)
    this.departmentService.getAllDepartment().subscribe(data => {
      this.departmentData = this.$common.generateTreeData(data, {
        keyName: "id",
        parentKeyName: "parentId"
      });
      this.expandDefault = this.departmentData[0].deptCode;
    });
  }

  private deallBtn(value) {
    this.selectAgent = value;
    this.dataHandler(value);
  }

  // 去重
  private dataHandler(value) {
    this.dataFinds = [];
    const obj: any = {};
    if (this.queueType !== "OUTER") {
      if(value) {
        value.filter(item => {
          if (!obj[item.deptName]) {
            this.dataFinds.push(item);
            obj[item.deptName] = true;
          }
        });
      }
    } else {
      if(value) {
        value.filter(item => {
          if (!obj[item.outOrgName]) {
            this.dataFinds.push(item);
            obj[item.outOrgName] = true;
          }
        });
      }
    }
    this.deptNameNum = this.dataFinds.length;
  }

  //删除
  private deleAgentBtn(index, rows) {
    this.selectAgent.splice(index, 1);
    this.dataHandler(this.selectAgent);
  }

  private changeAgent() {
    this.queueId = this.queueId;
    this.dialog.addAgent = true;
    const arr = this.selectAgent.map(item => {
      return { ...item, id: item.agentId, isAdmin: String(item.isAdmin) };
    });
    this.selectAgent = arr;

    // 监听add-agent选中的数据
    this.$nextTick(() => {
      const AddAgent: any = this.$refs["add-agent"];
      AddAgent.update(this.selectAgent);
      console.log('监听add-agent选中的数据--this.selectAgent', this.selectAgent)
      if (this.queueType === "SELF" || this.queueType === "LAWSUIT") { 
        return false;
      } else { AddAgent.refreshData(); }
    });
  }

  //提交经办人
  private commit() {
    if (!this.validate()) {
      return false;
    }
    const from: any = this.$refs.numberValidateForm;
    from.validate(valid => {
      if (!valid) return false;

      if (this.queueType !== "OUTER") this.NoOrgOutCommit();
      else this.OrgOutCommit(); // 外包
    });
  }

  // 自催队列
  private NoOrgOutCommit() {
    this.queueService
      .handlerSetting({
        handleSet: this.selectAgent,
        queueId: this.queueId,
        remark: this.numberValidateForm.remark
      })
      .subscribe(
        data => {
          this.$message.success("修改经办人成功!");
          // 刷新列表
          this.refreshList();
          // 关闭
          this.close();
          // this.departmentData = []  // 清空el-tree
          this.selectAgent = []
        },
        ({ msg }) => {}
      );
  }

  // 外包队列
  private OrgOutCommit() {
    this.selectAgent.map(item => {
      item.agentId = item.id;
      item.realName = item.outOrgName;
      item.handCode = item.divisionCode;
      item.caseSwitch = item.caseSwitch;
    });
    this.NoOrgOutCommit();
  }

  //校验经办人
  private validate() {
    let validate = true;
    if (this.selectAgent.length === 0) {
      this.$message.error("请至少选择一个经办人！");
      validate = false;
      return false;
    }
    if (this.showGuzhi) {
      this.selectAgent.every((item, index) => {
        //校验固值和比例
        if (!this.$validator.naturalNumber(item.fixedCount)) {
          this.$message.error(`第${index + 1}条固值需要为0或者正整数`);
          validate = false;
          return false;
        }
        item.fixedCount = Number(item.fixedCount);

        if (item.proportion === "" || item.proportion === null) {
          return true;
        } else if (
          !this.$validator.percentTwoDecimal(item.proportion) ||
          item.proportion === 0
        ) {
          this.$message.error(`第${index + 1}条比例需为0-100的两位数小数`);
          validate = false;
          return false;
        }
        item.proportion = Number(item.proportion);

        let totalProportion: any = 0;
        this.selectAgent.forEach(item1 => {
          totalProportion += Number(item1.proportion);
        });
        totalProportion = totalProportion === 0 ? "" : totalProportion;
        if (totalProportion !== 100 && totalProportion !== "") {
          this.$message.error("经办比例之和为空或等于100");
          validate = false;
          return false;
        }
        return true;
      });
    }
    return validate;
  }

  private handleSizeChange(val) {
    this.size = val;
  }

  private handleCurrentChange(val) {
    this.page = val;
  }
}
</script>

<style lang="less" scoped>
.pickTable {
  margin-left: -10px;
  width: 100% !important;
}
.txtBox {
  width: 100%;
  margin-top: -20px;
  line-height: 30px;
  padding: 5px 10px;
  box-sizing: border-box;
  background-color: #eee;
  color: #666;
}
.texatBox {
  width: 100%;
  margin-top: 10px;
}
.page.agent-manage {
  .col-span-2 {
    padding: 0;
  }
  .add-org {
    padding: 10px 20px;
    text-align: right;
    border-bottom: solid 1px #e4e4e4;
  }
  .org-tree {
    border: solid 1px #e4e4e4;
    min-height: 600px;
  }
  .col-span-10 {
    border: 1px solid #e4e4e4;
    border-left: none;
  }
  .col-span-12 {
    border: 1px solid #e4e4e4;
  }
  .title {
    padding-left: 10px;
    font-size: 16px;
  }

  .paginBox {
    width: 100%;
    height: 100%;
    overflow: hidden;
    .paginn {
      margin: 10px 15px 0px 0px;
      float: right;
    }
  }

}
</style>
<style lang="less">
.input-style .el-form-item__label{
  width: 116px !important;
}
#expireDay .el-form-item__label{
  width: 250px !important;
}
.team-note {
  .el-form-item__content {
    display: flex;
  }
}
.lockEndDate {
  margin-left: 64px;
}
.isTeamUse {
  .el-form-item__label {
    font-size: 14px !important;
    margin-left: -10px;
  }
  .el-form-item__content {
    margin-left: 0 !important;
  }
}
.queueRemark {
  margin-top: 20px;
}
.input-style {
  display: flex !important;
  .el-form-item__label {
    width: 106px !important;
  }
  .el-input {
    width: 100% !important;
  }
}
</style>
